<template>
  <el-form
    ref="formRef"
    :show-label="false"
    :show-require-mark="false"
    size="large"
    :model="formInline"
    :rules="rules"
    class="login-form"
  >
    <el-form-item prop="username">
      <el-input v-model="formInline.username" placeholder="请输入用户名">
        <template #prefix>
          <el-icon class="el-input__icon" size="18" color="#808695">
            <PersonOutline />
          </el-icon>
        </template>
      </el-input>
    </el-form-item>
    <el-form-item prop="password">
      <el-input
        v-model="formInline.password"
        type="password"
        show-password
        placeholder="请输入密码"
        @keyup.enter="handleSubmit"
      >
        <template #prefix>
          <el-icon class="el-input__icon" size="18" color="#808695">
            <LockClosedOutline />
          </el-icon>
        </template>
      </el-input>
    </el-form-item>

    <div class="flex items-center justify-between forget">
      <div class="flex-initial">
        <el-checkbox v-model:checked="autoLogin">自动登录</el-checkbox>
      </div>
    </div>

    <el-form-item :show-label="false">
      <el-button
        class="w-full"
        type="primary"
        @click="handleSubmit"
        size="large"
        :loading="loading"
        round
      >
        登录
      </el-button>
    </el-form-item>
  </el-form>
</template>

<script lang="ts" setup>
  import { computed, onMounted, reactive, ref } from 'vue';
  import { useRoute, useRouter } from 'vue-router';
  import { useUserStore } from '@/store/modules/user';
  import { ElMessage } from 'element-plus';
  import { ResultEnum } from '@/enums/httpEnum';
  import { PageEnum } from '@/enums/pageEnum';
  import { getGlobalConfig } from '@/api/common';
  import { useGlobSetting } from '@/hooks/setting';
  import { storage } from '@/utils/Storage';
  import { useConfigStore } from '@/store/modules/config';
  import { EventSourcePolyfill } from 'event-source-polyfill';
  import { IListItem, useMessageStore } from '@/store/modules/message';
  import { PersonOutline, LockClosedOutline } from '@vicons/ionicons5';
  import { CodeOutlined } from '@vicons/antd';

  const formRef = ref();
  const loading = ref(false);
  const autoLogin = ref(true);
  const LOGIN_NAME = PageEnum.BASE_LOGIN_NAME;
  const eventSource = ref();

  const formInline = reactive({
    username: 'superadmin',
    password: '000000',
  });

  const rules = {
    username: { required: true, message: '请输入用户名', trigger: 'blur' },
    password: { required: true, message: '请输入密码', trigger: 'blur' },
  };
  const emit = defineEmits(['goRegister']);
  const userStore = useUserStore();
  const configStore = useConfigStore();
  const guestId = ref();

  const router = useRouter();
  const route = useRoute();
  const globSetting = useGlobSetting();
  const messageStore = useMessageStore();

  const { apiUrl } = globSetting;

  const getToken = computed(() => {
    return userStore.getToken;
  });

  const handleSubmit = () => {
    formRef.value.validate(async (valid) => {
      if (valid) {
        loading.value = true;
        try {
          const { code, msg } = await userStore.login(formInline);
          if (code == ResultEnum.SUCCESS) {
            //监听消息
            // createEventSource();
            const toPath = decodeURIComponent((route.query?.redirect || '/') as string);
            ElMessage.success('登录成功，即将进入系统');
            if (route.name === LOGIN_NAME) {
              router.replace('/');
            } else router.replace(toPath);
          } else {
            ElMessage.error(msg || '登录失败');
          }
        } finally {
          loading.value = false;
        }
      } else {
        ElMessage.error('请填写完整信息');
      }
    });
  };

  const createEventSource = () => {
    if (!window.EventSource) {
      console.log('你的浏览器不支持SSE');
      return;
    }
    if (!getToken.value) return;
    eventSource.value = new EventSourcePolyfill(`${apiUrl}/sse/conn`, {
      headers: {
        'ACCESS-TOKEN': getToken.value
      },
    });

    /*
     * open：订阅成功（和后端连接成功）
     */
    eventSource.value.addEventListener('open', function () {
      console.log('open successfully');
    });
    /*
     * message：后端返回信息，格式可以和后端协商
     */
    eventSource.value.addEventListener('message', function (e) {
      const res = e.data && JSON.parse(e.data);
      console.log('🚀 ~ file: App.vue:97 ~ res:', res);
      const { body } = res;
      if (body) {
        messageStore.pushMessage([body] as IListItem[]);
      }
      console.log(e.data);
    });
    /*
     * error：错误（可能是断开，可能是后端返回的信息）
     */
    eventSource.value.addEventListener('error', function (err) {
      console.log(err);
      // 类似的返回信息验证，这里是实例
      err && err.status === 401 && console.log('not authorized');
    });
  };
</script>

<style lang="scss" scoped>
  .forget {
    margin-bottom: 16px;
    margin-top: -10px;
  }
  .login-form {
    .el-input {
      --el-input-border-radius: 20px !important;
    }
  }
</style>
